import axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { getToken, setToken, removeToken } from './auth'
import { ResultEnum } from '../enums/ResultEnum'
import { ElMessage } from 'element-plus'
const service = axios.create({
	baseURL: import.meta.env.VITE_APP_BASE_API,
	timeout: 60000,
	headers: { 'Content-Type': 'application/json;charset=utf-8' },
})

// 请求拦截器
service.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		const accessToken = getToken()
		// 如果 Authorization 设置为 no-auth，则不携带 Token，用于登录、刷新 Token 等接口
		if (config.headers.token !== 'no-auth') {
			config.headers.token = accessToken
			// 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VyU3RhdHVzIjoiMSIsImxvZ2luUHdkIjoiIiwiaXNJbml0aWFsTG9naW4iOmZhbHNlLCJ1c2VyUGhvbmUiOiIxODk4MjAxNzI1MyIsImRqRXhwaXJlc0luIjoiMjAyNS0wMS0wMlQxNTowMzo0Ni41ODUiLCJkakNyZWF0ZVRpbWUiOiIyMDI1LTAxLTAyVDE0OjMzOjQ2LjU4NSIsImlzQWRtaW4iOiIxIiwidXNlck5hbWUiOiJqeXRlc3QiLCJ1c2VySWQiOiJjZGUyZDRiY2Q2ZjU0ODZlOWIzN2MwNTg5ZmI2N2FiMyIsImV4cGlyZWRUaW1lIjoxNzM1ODEwNDI2NTg1LCJyZWFsTmFtZSI6IuiCluiLpeawtCIsImFyZWFDb2RlIjoiNTEwMTg1MDAwMDAwIiwidXNlckxldmVsIjoiMyIsImFyZWFOYW1lIjoi5oiQ6YO95biCL-eugOmYs-W4giIsImNyZWF0ZVRpbWUiOjE3MDMxNDU2MzYwMDAsImxvZ2luTmFtZSI6Imp5dGVzdCIsInVzZXJNYWlsIjoiIiwic3RhdGUiOiIxIn0.BGfL3TA3RoYF4Jvbr0beWoJf2Dv_HOTv3FnOc4N7j9i0kmxdODT_33ga-lLdnlV6rysyyB_IIvH_4IMDQs_oQw9OtICW6NYhLLOF0vFcuAmfBCfNgf_P7gCm1Bca5RFMz-RHh6aK41w9ktauZ8NwcHRBaTu59XzBK1hqAMy19dxOc7hsWMUUPaWhHWsGMA_KqwkoiKiJKtofkcavKWYGCY2c6io3IriDCq1kCgzAwZYUXZxCZlHgR_iZKZ3Nlar-t05WU2X0MF4QRIwRA4lz3C0bRmRGIB5nMn4t4yvQz0rLsSlJw-jLpEJbtgIx-2027CcPd16Du3rkdN22potQVA'
		} else {
			delete config.headers.token
		}
		return config
	},
	(error) => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		// 如果响应是二进制流，则直接返回，用于下载文件、Excel 导出等
		if (response.config.responseType === 'blob') {
			return response
		}
		// const { code, data, msg } = response.data
		// 如果服务器正确返回
		if (response.data.code == 200) {
			return response.data
		}
		if (response.data.code == 501) {
			ElMessage.error('登录过期，请刷新页面')
			removeToken()
		}
		return Promise.reject(new Error(response.data || 'Error'))
	},
	async (error: any) => {
		if (error) {
			const { code, msg } = error.response.data
			ElMessage.warning(code)

			// token 过期，跳转登录页
			if (code == '501') {
				ElMessage.error('登录过期，请刷新页面')
				removeToken()
				// setToken('')
				// window.location.reload()
			} else {
				ElMessage.error(msg || '系统出错')
			}
		}
		return Promise.reject(error.message)
	}
)

export default service
